/*
 * Copyright (c) 2005,2018, EVECOM Technology Co.,Ltd. All rights reserved.
 *
 * EVECOM PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.ruoyi.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author Simi Rao
 * @description
 * @created 2023/2/22
 */
public class FeeManagerExecutorConfig implements Executor {

//    @Bean("exportServiceExecutor")
//    public ThreadPoolTaskExecutor exportServiceExecutor() {
//        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
//        taskExecutor.setCorePoolSize(Runtime.getRuntime().availableProcessors() * 2);
//        taskExecutor.setAllowCoreThreadTimeOut(true);
//        taskExecutor.setMaxPoolSize(50);
//        taskExecutor.setQueueCapacity(500);
//        taskExecutor.setKeepAliveSeconds(1000);
//        taskExecutor.setThreadNamePrefix("export-service-");
//        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
//        taskExecutor.initialize();
//        return taskExecutor;
//    }
//
//    @Override
//    public void execute(Runnable command) {
//        execute(command);
//    }
    /**
     * 线程池
     */
    public static ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

    /**
     * 配置
     */
    static {
        //线程数量
        executor.setCorePoolSize(5);
        // 配置最大线程数
        executor.setMaxPoolSize(20);
        // 配置缓存队列大小
        executor.setQueueCapacity(100);
        // 空闲线程存活时间
        executor.setKeepAliveSeconds(200);
        executor.setThreadNamePrefix("event-executor-thread");
        // 线程池对拒绝任务的处理策略：这里采用了CallerRunsPolicy策略，当线程池没有处理能力的时候，该策略会直接在execute方法的调用线程中运行被拒绝的任务；如果执行程序已关闭，则会丢弃该任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //该方法用来设置 线程池关闭 的时候 等待 所有任务都完成后，再继续 销毁 其他的 Bean，这样这些 异步任务 的 销毁 就会先于 数据库连接池对象 的销毁
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 设置线程池中任务的等待时间，如果超过这个时候还没有销毁就强制销毁，以确保应用最后能够被关闭，而不是被没有完成的任务阻塞
        executor.setAwaitTerminationSeconds(60);
        //初始化
        executor.initialize();
    }

    /**
     * 执行
     */
    public void execute(Runnable task) {
        executor.execute(task);
    }
}
